const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const session = require('express-session');
const db = require('./models');
const wechatRouter = require('./routes/wechat');
const adminRouter = require('./routes/admin');

const app = express();

// 视图引擎配置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 使用默认分隔符
app.set('view options', {});

// 中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false } // 生产环境应设置为true并启用HTTPS
}));

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));
app.use('/views/test', express.static(path.join(__dirname, 'views/test')));

// 路由
app.use('/wechat', wechatRouter);
app.use('/admin', adminRouter);

// 微信消息解析中间件
app.use('/wechat', express.text({ type: 'text/xml' }));
app.use('/wechat', express.json({ type: 'application/json' }));
app.use('/wechat', express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
  res.send('微信推送服务运行中');
});

// 测试数据库连接
db.sequelize.authenticate()
  .then(() => {
    console.log('数据库连接成功');
    return db.sequelize.sync();
  })
  .then(() => {
    console.log('数据库同步完成');
  })
  .catch(err => {
    console.error('数据库连接失败:', err);
  });


const scheduleService = require('./services/scheduleService');

const PORT = process.env.PORT || 3000;
app.listen(PORT, async () => {
  console.log(`服务已启动，监听端口 ${PORT}`);
  // 初始化定时任务
  try {
    await scheduleService.initAllSchedules();
    console.log('定时任务初始化完成');
  } catch (err) {
    console.error('定时任务初始化失败:', err);
  }
});

module.exports = app;